package org.example.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.http.MediaType;
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;


@Component
@Slf4j
public class HttpUtil {

    @Resource
    private RestTemplate restTemplate;


    public String post(String url, String bodyContent, MultiValueMap<String, String> params, MediaType mediaType,
                       String userName, String password) {
        //BasicAuth认证
        restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor(userName, password));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);
        HttpEntity<String> request = new HttpEntity<>(bodyContent, headers);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParams(params);
        return restTemplate.postForObject(builder.toUriString(), request, String.class);
    }

    public String put(String url, String bodyContent, MediaType mediaType, String userName, String password) {
        restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor(userName, password));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);
        HttpEntity<String> request = new HttpEntity<>(bodyContent, headers);
        ResponseEntity<String> res = restTemplate.exchange(url, HttpMethod.PUT, request, String.class);
        return res.getBody();
    }

    public String delete(String url, String userName, String password) {
        restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor(userName, password));
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Object> requestEntity = new HttpEntity<>(new LinkedMultiValueMap<>(), headers);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, String.class);
        return exchange.getBody();
    }

    public ResponseEntity<String> putWithFile(String url, String userName, String password,
                                              File file) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 创建请求体，并添加文件
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", new FileSystemResource(file));

        // 创建HttpEntity
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 发送PUT请求
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class);

        return response;
    }


    public String get(String url, String userName, String password) {
        restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor(userName, password));
        ResponseEntity<Object> forEntity = restTemplate.getForEntity(url, Object.class);
        List<String> styles = getStyleNames(forEntity.getBody());
        return styles.toString();
    }

    private static List<String> getStyleNames(Object body) {
        List<String> styles = new ArrayList<>();
        if (body instanceof Map) {
            Map<String, Object> map1 = (Map<String, Object>) ((Map<String, Object>) body).get("styles");
            if (map1.get("style") instanceof List) {
                for (Object map : (List<?>) map1.get("style")) {
                    if (map instanceof Map) {
                        styles.add(((Map<String, String>) map).get("name"));
                    }
                }
            }
        }
        return styles;
    }

    public class BasicAuthInterceptor implements Interceptor {
        private String credentials;


        public BasicAuthInterceptor(String user, String password) {
            this.credentials = Credentials.basic(user, password);
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Request authenticatedRequest = request.newBuilder()
                    .header("Authorization", credentials).build();
            return chain.proceed(authenticatedRequest);
        }
    }

    public String deleteWithJson(String url, Object json, String username, String password) {
        OkHttpClient client = getOkHttpClient(username, password);
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url(url)
                .delete(body)
                .addHeader("content-type", "application/json")
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                assert response.body() != null;
                String bodyStr = new String(response.body().bytes());
                log.info("HTTP远程调用》》》 url:{} obj:{}", url, json);
                return bodyStr;
            } else {
                throw new RuntimeException("HTTP远程调用失败，url=" + url + "，obj=" + json + "，response=" + response.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("HTTP远程调用失败，url：" + url + "，obj：" + json, e);
            throw new RuntimeException(e);
        }
    }

    public String postWithJson(String url, Object obj, String username, String password) {
        String json = obj != null ? JSONUtil.toJsonStr(obj) : "";
        OkHttpClient client = getOkHttpClient(username, password);
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("content-type", "application/json")
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                assert response.body() != null;
                String bodyStr = new String(response.body().bytes());
                log.info("HTTP远程调用》》》 url:{} obj:{}", url, json);
                return bodyStr;
            } else {

                throw new RuntimeException("HTTP远程调用失败，url=" + url + "，obj=" + json + "，response=" + response.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("HTTP远程调用失败，url：" + url + "，obj：" + json, e);
            throw new RuntimeException(e);
        }
    }

    private OkHttpClient getOkHttpClient(String admin, String geoserver) {
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new BasicAuthInterceptor(admin, geoserver))
                .connectTimeout(45, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(
                        5, 2, TimeUnit.MINUTES))
                .build();
        return client;
    }

    public File downloadImageToFile(String url, String admin, String geoserver) {
        OkHttpClient okHttpClient = getOkHttpClient(admin, geoserver);
        Request request = new Request.Builder().url(url).build();
        String realFileName = getRealFileName(url);
        try (Response response = okHttpClient.newCall(request).execute();
             FileOutputStream outputStream = new FileOutputStream(realFileName);) {
            assert response.body() != null;
            outputStream.write(response.body().bytes());
            return new File(realFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String postWithXml(String url, String bodyStr,
                              String username, String password) {
        OkHttpClient client = getOkHttpClient(username, password);
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/xml");
        RequestBody body;
        if (StrUtil.isNotBlank(bodyStr)) {
            body = RequestBody.create(mediaType, bodyStr);
        } else {
            body = RequestBody.create(mediaType, "");
        }

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                assert response.body() != null;
                String res = new String(response.body().bytes());
                log.info("HTTP远程调用 >>> url:{} obj:{}", url, bodyStr);
                return res;
            } else {
                throw new RuntimeException("HTTP远程调用失败，url=" + url + "，obj=" + bodyStr + "，response=" + response.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("HTTP远程调用失败，url：" + url + "，obj：" + body, e);
            throw new RuntimeException(e);
        }
    }

    private static String getRealFileName(String url) {
        String path = getCurPath();
        // jar 文件不在 /tmp 目录里，jpg合格证在 tmp 目录
        if (!url.endsWith(".jar")) {
            path = path + "tmp" + File.separator;
        }
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }

        String fileName = url.substring(url.lastIndexOf("/") + 1);
        Pattern compile = Pattern.compile("^[a-zA-Z0-9]+[.]*[a-zA-Z0-9]+$");
        if (!compile.matcher(fileName).find()) {
            fileName = RandomUtil.randomString(6) + ".jpg";
        }

        return path + fileName;
    }

    // 最后一个字符是一个 '/'
    public static String getCurPath() {
        String path = HttpUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        if (path.startsWith("file:/")) {
            path = path.replace("file:/", "")
                    .replace("!/BOOT-INF/classes!", "")
                    .replace("/target/classes", "");
            String[] split = path.split("/");
            StringBuilder sb = new StringBuilder();
            for (String s : split) {
                if (!s.endsWith(".jar") && !"".equals(s)) {
                    sb.append(s).append("/");
                }
            }
            path = sb.toString();
        }
        return path;


    }

    // 获取项目根目录
    public static void getPath() {
        File file = new File(".");
        String path = file.getAbsolutePath().substring(0, file.getAbsolutePath().length() - 1);
        System.out.println(path);
    }

    public static void main(String[] args) {
        getPath();
    }
}
